#pragma once

#include "strategy/strategy_base.h"
#include <deque>
#include <numeric>

// 简单移动平均策略
class SimpleMaStrategy : public StrategyBase {
public:
    SimpleMaStrategy(int short_period = 5, int long_period = 20)
        : short_period_(short_period)
        , long_period_(long_period) {}

    void initialize() override {
        short_ma_prices_.clear();
        long_ma_prices_.clear();
        position_ = 0;
    }

    void on_market_data(const MarketData& data) override {
        // 更新短期MA
        short_ma_prices_.push_back(data.close);
        if (short_ma_prices_.size() > short_period_) {
            short_ma_prices_.pop_front();
        }

        // 更新长期MA
        long_ma_prices_.push_back(data.close);
        if (long_ma_prices_.size() > long_period_) {
            long_ma_prices_.pop_front();
        }

        // 当收集到足够的数据时开始生成信号
        if (short_ma_prices_.size() == short_period_ && 
            long_ma_prices_.size() == long_period_) {
            
            double short_ma = std::accumulate(short_ma_prices_.begin(), 
                                            short_ma_prices_.end(), 0.0) / short_period_;
            double long_ma = std::accumulate(long_ma_prices_.begin(), 
                                           long_ma_prices_.end(), 0.0) / long_period_;

            Signal signal;
            signal.symbol = data.symbol;
            signal.timestamp = data.timestamp;
            signal.price = data.close;

            // 金叉：短期MA上穿长期MA
            if (short_ma > long_ma && position_ <= 0) {
                signal.type = SignalType::BUY;
                signal.quantity = 1.0;  // 简单起见，固定交易量
                position_ = 1;
                if (signal_callback_) {
                    signal_callback_(signal);
                }
            }
            // 死叉：短期MA下穿长期MA
            else if (short_ma < long_ma && position_ >= 0) {
                signal.type = SignalType::SELL;
                signal.quantity = 1.0;
                position_ = -1;
                if (signal_callback_) {
                    signal_callback_(signal);
                }
            }
        }
    }

    void finalize() override {
        // 回测结束时平掉所有仓位
        if (position_ != 0 && !short_ma_prices_.empty()) {
            Signal signal;
            signal.symbol = ""; // 使用最后一个交易的symbol
            signal.timestamp = ""; // 使用最后的时间戳
            signal.price = short_ma_prices_.back();
            signal.type = position_ > 0 ? SignalType::SELL : SignalType::BUY;
            signal.quantity = std::abs(position_);
            
            if (signal_callback_) {
                signal_callback_(signal);
            }
        }
    }

private:
    int short_period_;
    int long_period_;
    std::deque<double> short_ma_prices_;
    std::deque<double> long_ma_prices_;
    int position_;  // 1: 多头, -1: 空头, 0: 空仓
};